package com.walkerma.library;

import java.util.ArrayList;
import android.content.ContentProviderOperation;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.provider.ContactsContract.*;
import android.provider.ContactsContract.CommonDataKinds.*;
import android.text.TextUtils;

public class PhoneBook {
	public static Cursor getNumberCursor(Context context, String number){
		Uri lookupUri = Uri.withAppendedPath(
				PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number));
		String[] mPhoneNumberProjection = {
				PhoneLookup._ID, PhoneLookup.NUMBER, 
				PhoneLookup.DISPLAY_NAME};
		return context.getContentResolver().query(
				lookupUri,mPhoneNumberProjection, null, null, null);
	}


	public static Cursor getAllContacts(Context context){
		return context.getContentResolver().query(
				Contacts.CONTENT_URI, null, null, null, null);	
	}


	public static Cursor getAllNamePhone(Context context){
		String[] projection = new String[] {Phone.DISPLAY_NAME, Phone.NUMBER};
		Cursor cr = context.getContentResolver().query(Phone.CONTENT_URI,
				projection, null, null, null);
		return cr;
	}


	public static String[] getContactsColumnsName(Context context){
		Cursor row = context.getContentResolver().query(
				Contacts.CONTENT_URI,null, null, null, null);
		int nTotal = row.getColumnCount();
		String[] contactsName = new String[nTotal];
		for(int i=0; i<nTotal; i++)
			contactsName[i]= row.getColumnName(i);
		return contactsName;
	}


	public static Cursor getNameCursor(Context context, String name){
		String selection = Phone.DISPLAY_NAME + " LIKE '" + name +"%'";
		String[] projection = new String[] {Phone.NUMBER};
		Cursor cr = context.getContentResolver().query(Phone.CONTENT_URI,
				projection, selection, null, null);
		return cr;
	}


	public static String getNameFromNumber(Context context, String number){
		Cursor cr = getNumberCursor(context, number);
		if(cr == null) return "";
		if(cr.getCount() == 0)
			return "";
		else{
			cr.moveToFirst();
			return cr.getString(cr.getColumnIndex(PhoneLookup.DISPLAY_NAME));
		}
	}


	public static boolean contactExists(Context context, String number){
		Cursor cr = getNumberCursor(context, number);
		if(cr == null) return false;
		if(cr.getCount()>0)
			return true;
		else
			return false;
	}


	public static boolean isMobileNumber(String number){
		if(TextUtils.isEmpty(number)) return false;
		if(number.equals("Private")) return false;
		if(number.startsWith("0")) return false;
		if((number.length() == 11) && number.startsWith("1")) return true;
		if(number.length() <= 6 ) return true; //<=6 for unit number
		return false;	
	}


	public static boolean isRegularMobileNumber(String number){
		if(!isMobileNumber(number)) return false;
		if(number.length() == 11)
			return true;
		else
			return false;
	}


	public static boolean isContactMobileNumber(
			Context context, String number){
		if(contactExists(context, number) == false) return false;
		return isMobileNumber(number);
	}


	public static ArrayList<ContentProviderOperation> buildOps(){
		ArrayList<ContentProviderOperation> ops = 
				new ArrayList<ContentProviderOperation>();
		ops.add(ContentProviderOperation
				.newInsert(RawContacts.CONTENT_URI)
				.withValue(RawContacts.ACCOUNT_TYPE, null)
				.withValue(RawContacts.ACCOUNT_NAME, null)
				.build());
		return ops;
	}	


	public static ArrayList<ContentProviderOperation> addName(
			ArrayList<ContentProviderOperation> ops, String name){
		if(TextUtils.isEmpty(name)) return null;
		ops.add(ContentProviderOperation
				.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, 0)
				.withValue(Data.MIMETYPE,
						StructuredName.CONTENT_ITEM_TYPE)
						.withValue(StructuredName.DISPLAY_NAME,
								name).build());
		return ops;
	}


	public static ArrayList<ContentProviderOperation> addMobileNumber(
			ArrayList<ContentProviderOperation> ops, String phone){
		if(TextUtils.isEmpty(phone)) return null;
		ops.add(ContentProviderOperation
				.newInsert(Data.CONTENT_URI)
				.withValueBackReference(
						Data.RAW_CONTACT_ID, 0)
						.withValue(Data.MIMETYPE,
								Phone.CONTENT_ITEM_TYPE)
								.withValue(Phone.NUMBER, phone)
								.withValue(Phone.TYPE, Phone.TYPE_MOBILE)
								.build());
		return ops;
	}


	public static ArrayList<ContentProviderOperation> addHomeNumber(
			ArrayList<ContentProviderOperation> ops, String homeNumber){
		if(TextUtils.isEmpty(homeNumber)) return null;
		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, 0)
				.withValue(Data.MIMETYPE,
						Phone.CONTENT_ITEM_TYPE)
						.withValue(Phone.NUMBER, homeNumber)
						.withValue(Phone.TYPE, Phone.TYPE_HOME)
						.build());
		return ops;
	}	


	public static ArrayList<ContentProviderOperation> addWorkNumber(
			ArrayList<ContentProviderOperation> ops, String workNumber){
		if(TextUtils.isEmpty(workNumber)) return null;
		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, 0)
				.withValue(Data.MIMETYPE,
						Phone.CONTENT_ITEM_TYPE)
						.withValue(Phone.NUMBER, workNumber)
						.withValue(Phone.TYPE, 
								Phone.TYPE_WORK)
								.build());
		return ops;
	}


	public static ArrayList<ContentProviderOperation> addEmailID(
			ArrayList<ContentProviderOperation> ops, String emailID){
		if(TextUtils.isEmpty(emailID)) return null;
		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, 0)
				.withValue(Data.MIMETYPE,
						Email.CONTENT_ITEM_TYPE)
						.withValue(Email.DATA, emailID)
						.withValue(Email.TYPE, Email.TYPE_WORK)
						.build());
		return ops;
	}


	public static ArrayList<ContentProviderOperation> addCompanyTitle(
			ArrayList<ContentProviderOperation> ops, 
			String company, String jobTitle){
		if(TextUtils.isEmpty(company)||jobTitle.isEmpty()) return null;
		ops.add(ContentProviderOperation.newInsert(Data.CONTENT_URI)
				.withValueBackReference(Data.RAW_CONTACT_ID, 0)
				.withValue(Data.MIMETYPE,
						Organization.CONTENT_ITEM_TYPE)
						.withValue(Organization.COMPANY, company)
						.withValue(Organization.TYPE, Organization.TYPE_WORK)
						.withValue(Organization.TITLE, jobTitle)
						.withValue(Organization.TYPE, Organization.TYPE_WORK)
						.build());
		return ops;
	}


	public static boolean deleteContact(
			Context context, String phone, String name) {
		Uri contactUri = Uri.withAppendedPath(
				PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
		Cursor row = context.getContentResolver().query(
				contactUri, null, null, null, null);
		if(row==null) return false;
		if(row.getCount()==0) return false;
		try {
			row.moveToFirst();
			while(true){
				if (row.getString(row.getColumnIndex(
						PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) {
					String lookupKey = row.getString(
							row.getColumnIndex(Contacts.LOOKUP_KEY));
					Uri uri = Uri.withAppendedPath(
							Contacts.CONTENT_LOOKUP_URI, lookupKey);
					context.getContentResolver().delete(uri, null, null);
					return true;
				}
				if(row.isLast())
					break;
				else
					row.moveToNext();
			}
		} catch (Exception e) {
			return false;
		}finally {
			row.close();
		}
		return false;
	}
}
